
(function () {
    CAAT.DEBUG_VIEWPORT = 1;
	
    CAAT.SceneGameCtn = function () {
        CAAT.SceneGameCtn.superclass.constructor.call(this);
        return this;
    };

    var self;
    var staticBg;
    var runBg;
    var runBgVel = 0;

    var brickActor;
    var brickSize;
    var brickImg;

    var actor;
    var actor2;
    var censoredActor;

    var stonesArray;
    var stonesList;
    var maxStone;
    var curStone;

    var bgActor2;
    var bgActor1;

    var startTime;
    
	CAAT.SceneGameCtn.prototype = {
		create: function(director) {
			self = this;
			this.director = director;
			this.sceneTime = 0;
			var menuWidth = 80;
			var menuHeight = 50;
			
			var menuImage = new CAAT.Foundation.SpriteImage().initialize(director.getImage('menuBattleButton'), 1, 2 );
			this.paused = false;
			this.menuFunction = function(){
				self.paused = true;
				self.cacheAsBitmap(self.sceneTime,CAAT.Foundation.Actor.CACHE_DEEP);
			}
			this.menuButton = new CAAT.Button().initialize(this.director,menuImage,0,1,1,0,self.menuFunction)
				.setLocation((CANVAS_WIDTH-menuWidth-20),0)
				.setScaleAnchored(menuWidth/menuImage.singleWidth,menuHeight/menuImage.singleHeight,0,0);

			var controlpanelHeight = 200;

			censoredActor = genCensored(director.getImage('censored'));
			self.addChild(censoredActor);

			this.setBounds(0,0,CANVAS_WIDTH,CANVAS_HEIGHT)
				.setFillStyle("#ccccff");

			runBgVel = -2;
			runBg = new CAAT.ActorContainer()
				.setBounds(0, 0, this.width*2, this.height-controlpanelHeight)
            	.enableEvents(false);
            self.addChild(runBg);

            var bgImg = this.director.getImage("background-1");
			bgActor1 = new CAAT.ActorContainer()
				.setBounds(0, 0, this.width, this.height-controlpanelHeight)
				.setBackgroundImage(bgImg)
            	.setScaleAnchored(this.width/bgImg.width, (this.height-controlpanelHeight)/bgImg.height, 0, 0)
            	.enableEvents(false);

            bgImg = this.director.getImage("background-1");
            bgActor2 = new CAAT.ActorContainer()
				.setBounds(this.width, 0, this.width, this.height-controlpanelHeight)
				.setBackgroundImage(bgImg)
            	.setScaleAnchored(this.width/bgImg.width, (this.height-controlpanelHeight)/bgImg.height, 0, 0)
            	.enableEvents(false);

            staticBg = new CAAT.ActorContainer()
				.setBounds(0, 0, this.width, this.height-controlpanelHeight)
            	.enableEvents(false);
            self.addChild(staticBg);

            runBg.addChild(bgActor1);
			runBg.addChild(bgActor2);

            this.controlPanel = new CAAT.ActorContainer()
				.setBounds(0, this.height-controlpanelHeight,this.width,this.height) 	
				.enableEvents(true);

			this.addChild(this.controlPanel);
			this.addChild(this.menuButton);

	        actor = new CAAT.PlayActor()
	            .create(director, 0.3, 200)
	           	.setLocation( 100, 200 );
	        staticBg.addChild(actor);

	        actor2 = new CAAT.GirlActor()
	        	.create(director, 0)
	            .setLocation( 600, 175 );
	        staticBg.addChild(actor2);

	        var jumbImage = new CAAT.Foundation.SpriteImage().initialize(director.getImage('jumbButton'), 1, 4 );
            
            var jumbButton = new CAAT.Button()
            	.initialize(director, jumbImage, 0, 1, 2, 3, function(button){
	            	actor.jump(self.sceneTime);
	            })
	            .setLocation(0,0);
            this.controlPanel.addChild(jumbButton);

            var rockImage = director.getImage('rock');
            
            stonesArray = [];
            var actionImage = new CAAT.Foundation.SpriteImage().initialize(director.getImage('actionButton'), 1, 4 );
            
            var rockPb;
            var actionButton = new CAAT.Button()
            	.initialize(director, actionImage, 0, 1, 2, 3, function(button){
            		//fap fap
            		if(curStone > 0) {
            			curStone--;
            			stonesList.removeStone();
	            		var i = stonesArray.length;
	            		stonesArray[i] = new CAAT.Actor()
	            			.setBackgroundImage(rockImage)
	            			.setLocation(actor.x + 50, actor.y + 50);
	            		stonesArray[i].idInArray = i;
	            		rockPb = new CAAT.Behavior.PathBehavior();
	            		rockPb.setFrameTime(self.sceneTime, 100*7)
		                    .setPath(
		                        new CAAT.PathUtil.Path()
		                            .beginPath(actor.x+50, actor.y+50)
		                            .addCubicTo(actor.x+50, actor.y+50, actor.x+150, actor.y+70, actor.x+250, actor.y+150)
		                            .endPath()
		                    )
		                    .addListener({
		                        behaviorExpired : function(behavior, time, actor) {
		                            actor.removeBehaviour(behavior);
		                            staticBg.removeChild(actor);
		                            stonesArray.splice(actor.idInArray, 1);
		                            console.log('ccc');
		                        }
		                    });
		                stonesArray[i].addBehavior(rockPb);
		                staticBg.addChild(stonesArray[i]);
		            }
	            })
	            .setLocation(self.controlPanel.width - actionImage.singleWidth, 0);
            this.controlPanel.addChild(actionButton);

			return this;
		},
		countDownTime : 3000,
		showStartText : false,

		update : function (director,time) {
			self.sceneTime = time;

			if(!actor.isStand && actor.x >= actor2.x){
				// XH
				actor.setStop();
				runBgVel = 0;
				console.log('thang');
				console.log(actor.x);
				console.log(actor2.x);
				censoredActor = genCensored(director.getImage('censored'));
	            self.addChild(censoredActor);
			}
			if(!actor.isStand && actor.currentHP <= 0){

				console.log('thua');
				actor.setStop();
				runBgVel = 0;
				actor.playAnimation("sad");
				
				censoredActor = genCensored(director.getImage('censored'));
	            self.addChild(censoredActor);
	            
				console.log(censoredActor);
	            console.log(actor.x);
			}

			if(stonesArray && stonesArray.length > 0) {
				for(var i = 0; i < stonesArray.length && brickActor.isHard; i++) {
					if(checkRectCollision(stonesArray[i], brickActor)) {
						runBg.removeChild(brickActor);
						brickActor.isHard = false;
						staticBg.removeChild(stonesArray[i]);
						stonesArray.splice(i, 1);
						i--;
					}
				}
			}

			if(!actor.isStand){
				runBg.x += runBgVel;
				if(runBg.x + self.width <= 0) {
					runBg.x += self.width;
					if(brickActor.isHard) {
						runBg.removeChild(brickActor);
					}
					brickActor.isHard = true;
					brickActor = genBrick(brickImg);
					runBg.addChild(brickActor);
					console.log('reset background');
					console.log(actor.x);
					console.log(actor2.x);
				}
				actor.x += actor.velocity;
				actor2.x += actor2.velocity;
				if(actor.AABB.x1 > brickActor.AABB.x && actor.AABB.x1 < brickActor.AABB.x1
					&& actor.AABB.y1 > brickActor.y + brickSize*0.3) {
					if(brickActor.isHard) {
						console.log('fucking stone');
						brickActor.isHard = false;
						runBg.removeChild(brickActor);
						actor.bePushBack(self.sceneTime);
					}
				}
			}

			var elapsedTime = time-startTime;
			this.elapsedTime = time-startTime;
			if(elapsedTime<self.countDownTime){
				if(!self.showStartText){
					self.showStartText = true;
					var startText = new CAAT.Foundation.ActorContainer().setBounds(CANVAS_WIDTH/2,20,50,50);
					startText.paint = function(director,time){
						
						var ctx = director.ctx;
						ctx.font = "20px Times New Roman";
						this.alpha = 0.7;
						var elapsedTime = self.elapsedTime;
						var currentWave;
						var distance =  (actor2.x - actor.x)>>0;
						var text = "distance: "+ distance + " m";
						// if(elapsedTime<self.countDownTime) currentWave = 0;
						// else currentWave = self.currentWave + 1;
						// var text = lang.sceneBattle.ID0[LANGUAGE]+ currentWave+"/"+self.waveNumber;
						// if(self.countDownTime-elapsedTime>0){
							// self.startText = lang.sceneBattle.ID1[LANGUAGE] +(1+(self.countDownTime-elapsedTime)/1000<<0)+ lang.sceneBattle.ID2[LANGUAGE];
						// }
						var height = 100
						if(!self.showStartText) {
							self.startText = "";
							height = 80;
						}	
						elapsedTime/=1000;
						var minute = ""+((elapsedTime/60)>>0);
						minute = (minute.length==2)? minute : "0"+minute;
						var second = ""+((elapsedTime%60)>>0);
						second = (second.length==2)? second : "0"+second;
						var timeText = minute +" : "+ second;
						var measure0 = ctx.measureText(timeText).width;
						var measure1 = ctx.measureText(text).width;
						// var measure2 = ctx.measureText(self.startText).width;
						var width = 30 + Math.max(measure0,measure1);
						
						ctx.fillStyle = "#00F";
						ctx.fillRect(-width/2,-20,width,height-20);
						ctx.fillStyle = "#0FF";
						ctx.fillText(timeText,-measure0/2,0);
						ctx.fillText(text,-measure1/2,25);
						// ctx.fillText(self.startText,-measure2/2,50);
					}
					self.addChild(startText);
				}
			}
		}, 

		reset: function(){
			self.removeChild(censoredActor);
			startTime = self.sceneTime;
			this.sceneTime = 0;
			var menuWidth = 80;
			var menuHeight = 50;
			
			var menuImage = new CAAT.Foundation.SpriteImage().initialize(self.director.getImage('menuBattleButton'), 1, 2 );
			this.paused = false;
			
			var controlpanelHeight = 200;

			runBgVel = -2;
			runBg
				.setBounds(0, 0, this.width*2, this.height-controlpanelHeight)
	        	.enableEvents(false);

	        var bgImg = this.director.getImage("background-1");
			bgActor1
				.setBounds(0, 0, this.width, this.height-controlpanelHeight)
				.setBackgroundImage(bgImg)
	        	.setScaleAnchored(this.width/bgImg.width, (this.height-controlpanelHeight)/bgImg.height, 0, 0)
	        	.enableEvents(false);

	        bgImg = this.director.getImage("background-1");
	        bgActor2
				.setBounds(this.width, 0, this.width, this.height-controlpanelHeight)
				.setBackgroundImage(bgImg)
	        	.setScaleAnchored(this.width/bgImg.width, (this.height-controlpanelHeight)/bgImg.height, 0, 0)
	        	.enableEvents(false);

	        staticBg
				.setBounds(0, 0, this.width, this.height-controlpanelHeight)
	        	.enableEvents(false);

	        maxStone = 4;

			brickSize = 50;
			brickImg = this.director.getImage('brick');
			if(!brickActor || !brickActor.isHard) {
		        brickActor = genBrick(brickImg);
		        runBg.addChild(brickActor);
	    	}

	        actor.reset(0.3, 200)
	           	.setLocation( 100, 200 );
	        
	        actor2.reset(0)
	            .setLocation( 600, 175 );

	        stonesArray = [];

	        curStone = maxStone = 4;
	        stonesList = [];
	        var rockImage = self.director.getImage('rock');
	        for(var i = 0; i < maxStone; i++) {
            	stonesList[i] = new CAAT.Foundation.Actor()
            		.setBackgroundImage(rockImage)
            		.setLocation(i*rockImage.width*1.2, rockImage.height*0.2);
            	this.addChild(stonesList[i]);
            }
            stonesList.removeStone = function() {
            	var n = stonesList.length;
            	if(n > 0) {
	            	self.removeChild(stonesList[n-1]);
	            	stonesList.splice(n-1, 1);
	            }
            }
            
	        return this;
	   }
	};
	extend(CAAT.SceneGameCtn, CAAT.ActorContainer);
	 
	//rect = { x, y, x1, y1 }
	//point = { x, y }
	var checkPointInRect = function (point, rect) {
		if(rect.x < point.x && point.x < rect.x1
			&& rect.y < point.y && point.y < rect.y1) {
			return true;
		}
		return false;
	}

	var r0 = new CAAT.Rectangle();
	var r1 = new CAAT.Rectangle();
	var checkRectCollision = function (e0, e1) {
		r0.setBounds( e0.AABB.x, e0.AABB.y, e0.AABB.width, e0.AABB.height );
		r1.setBounds( e1.AABB.x, e1.AABB.y, e1.AABB.width, e1.AABB.height );
		// console.log('e0: ' + e0.x + ' - ' + e0.y);
		// console.log('e1: ' + e1.x + ' - ' + e1.y);
		return r0.intersects(r1);
	}

	var genBrick = function(image) {
		var brick = new CAAT.Actor()
			.setBackgroundImage(image)
        	.setScaleAnchored(brickSize/image.width, brickSize/image.height, 0, 0)
        	.setLocation(self.width, runBg.height - 2*brickSize)
        	.enableEvents(false);
        brick.isHard = true;
        return brick;
    }

    var genCensored = function(image) {
    	var censored = new CAAT.Actor()
			.setBackgroundImage(image)
	    	.setScaleAnchored(self.width*0.5/image.width, self.height*0.5/image.height, 0, 0)
	    	.setLocation(self.width*0.5, self.height*0.3)
	    	.enableEvents(false);
	    return censored;
    }
   
})()